package org.baicaixiaozhan.springbootwebdemo2.domain;

import com.google.common.collect.ImmutableSet;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author baicaixiaozhan
 * @since 2021/1/29
 */
public enum UserPermissions {
    // 角色: 学生
    ROLE_STUDENT(ImmutableSet.of("read", "update")),
    // 角色: 老师
    ROLE_TEACHER(ImmutableSet.of("read", "add", "update")),
    // 角色: 管理员
    ROLE_ADMIN(ImmutableSet.of("read", "add", "update", "delete"));

    UserPermissions(Set<String> permissions) {
        this.permissions = permissions;
    }

    /**
     * 角色下可行的权限
     */
    private Set<String> permissions;

    public Set<String> getPermissions() {
        return permissions;
    }

    public Set<SimpleGrantedAuthority> getGrantedAuthorities() {
        final Set<SimpleGrantedAuthority> authorities = getPermissions().stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet());
        authorities.add(new SimpleGrantedAuthority(this.name()));
        return authorities;
    }
}
